# !/usr/bin/env python
# coding:utf-8
"""
    Author = 上善若水(QQ:564667570)
    Affiliation = Institute of Subtropical Agriculture, Chinese Academy of Sciences
    date = 'date'
"""

"""
自定义一个异常类,当list内元素长度超过10的时候抛出异常
"""
# Method_01
list_a = [1, 3, 45, 4, 9, 82, 12, 10, 32, 43, 51]

class MyError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return self.value

def main():
    try:
        if len(list_a) <= 10:
            print('list length is less than 10: ', len(list_a))
        else:
            raise MyError('List length is larger than 10')
    except Exception as e:
        print(e, ', elements are bigger than 10')
if __name__ == '__main__':
    main()


# Method_02
list_b = [1, 3, 45, 4, 9, 82, 12, 54, 88, 90, 65]
try:
    if len(list_b) >= 10:
        print('The length of List: ', len(list_b))
        raise IndexError('len(list_b) is bigger than 10')
    else:
        print('len(list_b) is smaller than 10')
except Exception as e:
    print(e)


"""
  2.思考如果对于多种不同的代码异常情况都要处理,又该如何去
     处理,自己写一个小例子
"""

list_a = [1, 0, 34, 7, 21]
try:
    num = int(input('please insert a number: '))
    print(num)
except ValueError as e:
    print(e)
try:
    f = open('ruoshui.py')
    raise IOError('no such file or directory')
except IOError as e:
    print(e)
try:
    print(list_a[8])
except IndexError as e:
    print(e)
try:
    for item in list_a:
        division = 16 / item
        print(division)
except ZeroDivisionError as e:
    print(e)

"""
  3.try-except和try-finally有什么不同,写例子理解区别
  4.写函数，检查传入字典的每一个value的长度，如果大于2，
     那么仅仅保留前两个长度的内容，并将新内容返回给调用者
     dic = {“k1”: "v1v1","k2":[11,22,33}}
"""
print("4.1 the code with try - except format")
try:
    div = 19 / 0
except ZeroDivisionError as e:
    print(e)

print("4.2 the code with try - except - finally format")
try:
    content = int(input('insert a number:'))
    num = 6 / content
except ZeroDivisionError as e:
    print(e)
else:
    print('your insert number is correct, not 0')
finally:
    print('Clean all data')

"""
  4.写函数，检查传入字典的每一个value的长度，如果大于2，
     那么仅仅保留前两个长度的内容，并将新内容返回给调用者
     dic = {“k1”: "v1v1","k2":[11,22,33}}
"""
def fun():
    dic = {"k1": 'v1v1', "k2":[11, 22, 33]}
    print(dic)
    try:
        for key in dic.keys():
            print(key)
            for value in dic.values():
                print(type(value))
                if type(value) is str:
                    del dic[key]
                    dic.update(dict(key=value[:2]))
                    print(dic)
                    raise (ValueError('invalid literal for int()'))
                else:
                    dic.update(dict(key=value[:2]))
                    raise TypeError('str object does not support item assignment')
    except Exception as e:
        print(e)

def main():
    fun()
if __name__ == '__main__':
    main()

